#!/bin/bash
ymlToVar() {
  export $(yq e -o props $1 | grep -vE "^[[:space:]]*#|^[[:space:]]*$" | awk -F ' = ' '{gsub(/\./, "_", $1); print $1"="$2}')
}

update_join_cmd() {
    local create_file=true
    local token=""
    local expire=""
    local certKey=""
    local new_file=false

    if [ -f /var/lib/vke/server/join-key ]; then
        token=$(cat /var/lib/vke/server/join-key | grep "token:" | awk '{print $2}')
        hash=$(cat /var/lib/vke/server/join-key | grep "hash:" | awk '{print $2}')
        certKey=$(cat /var/lib/vke/server/join-key | grep "certKey:" | awk '{print $2}')
        expire=$(cat /var/lib/vke/server/join-key | grep "expire:" | awk '{print $2}')
        if [ -n $token ]; then
            now=$(date +%s)
            let now=now+60
            if [ $now -lt $(date --date=$expire +%s) ]; then
                echo "has not expired, use exist token"
                create_file=false
            fi
        fi
    fi

    loop=0
    if [ $create_file == "true" ]; then
        new_file=true
        echo "create new token"
        while true; do
            token=$(kubeadm token create)
            expire=$(kubeadm token list | grep $token | awk '{print $3}')
            if [ -z "$token" ] || [ -z "$expire" ]; then
                let loop=loop+1
                if [ $loop -eq 100 ]; then
                   echo "create token timeout!!!"
                   exit
                fi
                sleep 3
            else
                break
            fi
        done
    fi


    if [ -z "$hash" ]; then
        new_file=true
        hash=$(openssl x509 -pubkey -in /etc/kubernetes/pki/ca.crt \
          | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //')
    fi

    loop=0
    if [ -z "$certKey" ]; then
        new_file=true
        echo "create new certKey"
        while true; do
            string=$(kubeadm init phase upload-certs --upload-certs)
            certKey=$(echo "$string" | tail -1)
            let loop=loop+1
            if [ -z "$certKey" ]; then
                let loop=loop+1
                if [ $loop -eq 100 ]; then
                   echo "create token timeout!!!"
                   exit
                fi
                sleep 3
            else
                break
            fi
        done
    fi

    if [ $new_file == "true" ]; then
        mkdir -p /var/lib/vke/server
        cat > /var/lib/vke/server/join-key << EOF
token: $token
hash: $hash
certKey: $certKey
expire: $expire
EOF
    fi
        kubectl delete configmap join-key --force > /dev/null 2>&1
    kubectl create configmap join-key --from-literal=token=$token --from-literal=hash=$hash --from-literal=certKey=$certKey

    echo "new token file:"
    echo "----------------------------------------------------"
    cat /var/lib/vke/server/join-key
    echo "----------------------------------------------------"
    echo "join new worker: "
    echo "    echo ${NODE_apiServerIp} ${K8S_apiServerName} >> /etc/hosts "
    echo "    kubeadm join api.k8s.local:6443 --token $token \ "
    echo "      --discovery-token-ca-cert-hash sha256:$hash"
    echo "join new controlPlane: "
    echo "    echo ${NODE_apiServerIp} ${K8S_apiServerName} >> /etc/hosts "
    echo "    kubeadm join api.k8s.local:6443 --token $token \ "
    echo "      --discovery-token-ca-cert-hash sha256:$hash \ "
    echo "      --control-plane --certificate-key $certKey \ "
    echo "      --apiserver-advertise-address  <node_internalIP>"
    echo "upgrade to controlPlane: "
    echo "    echo ${NODE_apiServerIp} ${K8S_apiServerName} >> /etc/hosts "
    echo "    kubeadm join api.k8s.local:6443 --token $token \ "
    echo "      --discovery-token-ca-cert-hash sha256:$hash \ "
    echo "      --control-plane --certificate-key $certKey"
}

create_join_cmd() {
    rm -f /var/lib/vke/server/join-key
        mkdir -p /var/lib/vke/server
        update_join_cmd
}


#=========================================================
K8S_vkeConfigPath=${K8S_vkeConfigPath:-'/etc/vke'}
ymlToVar ${K8S_vkeConfigPath}/k8s.conf
ymlToVar ${K8S_vkeConfigPath}/node.yaml

create_join_cmd
